﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System.IO;
using System;

public class ListFileProcessor {

    private string filePath;
    private Dictionary<string, string> fileDic = new Dictionary<string, string>();

    public ListFileProcessor(string path)
    {
        filePath = path;
    }

    public bool Init()
    {
        try { 
            StreamReader reader = File.OpenText(filePath);

            string line = reader.ReadLine();
            while(!string.IsNullOrEmpty(line))
            {
                string[] detail = line.Split(',');
                string path = detail[0];
                string md5 = detail[1];
                fileDic[path] = md5;
                line = reader.ReadLine();
            }

            reader.Close();
            reader.Dispose();
        }
        catch(Exception e)
        {
            Debug.LogError("Process file: " + filePath + " met errors. Details = " + e.ToString());
            return false;
        }

        return true;
    }

    // 参数是前一个版本
    public Dictionary<string, string> Compare(ListFileProcessor other, ref Dictionary<string, string> oldFilesCanBeDelete)
    {
        Dictionary<string, string> result = new Dictionary<string, string>();

        Dictionary<string, string> comparedDic = other.GetFileDic();
        foreach(KeyValuePair<string, string> entry in fileDic)
        {
            // changed files
            if (comparedDic.ContainsKey(entry.Key) && comparedDic[entry.Key] != entry.Value)
            {
                result.Add(entry.Key, entry.Value);
            }
            // added files
            else if (!comparedDic.ContainsKey(entry.Key))
            {
                result.Add(entry.Key, entry.Value);
            }
        }

        // files can be deleted in old revision
        foreach(KeyValuePair<string, string> entry in comparedDic)
        {
            if (fileDic.ContainsKey(entry.Key)) continue;

            oldFilesCanBeDelete.Add(entry.Key, entry.Value);
        }

        return result;
    }

    public Dictionary<string, string> GetFileDic()
    {
        return fileDic;
    }
}
